package com.ruoyi.common.utils.base;



import org.apache.commons.codec.binary.Base64;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;/*
 *
 * 2021-11-17 16:30
 *接口加密
 */

public class AesUtil {
    public static void main(String[] args) throws Exception {
        // aes + base  -->  aes + base
        String content =   "{\"mac\":\"123\",\"idfa\":\"123\",\"clientIp\":\"456\",insertTime\":\"test\"}";
        System.out.println("加密内容：" + content);
        String key = "123abccc";
        System.out.println("加密密钥和解密密钥：" + key);
        String encrypt = aesEncrypt(content, key);
        System.out.println("加密后：" +encrypt);
        String decrypt = AesDec.aesDecrypt(encrypt, "123abccc");
        System.out.println("解密后：" + decrypt);
    }

    /**
     * 编码
     * @param bstr
     * @return String
     */
    public static String Base64encode(byte[] bstr) {
        return Base64.encodeBase64String(bstr);
    }

    /**
     * 解码
     * @param str
     * @return string
     */
    public static byte[] Base64decode(String str) {
        return Base64.decodeBase64(str);
    }

    /*
     * AES加密
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        /*防止linux下 随机生成key*/
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(encryptKey.getBytes());
        kgen.init(128, random);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));

        return cipher.doFinal(content.getBytes("UTF-8"));
    }

    /**
     * AES加密为base 64 code
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return Base64encode(aesEncryptToBytes(content, encryptKey));
    }


}

